package org.vestbjergbyggecenter.Model;

import java.util.ArrayList;
import java.util.Iterator;

public class CategoryRecords {
	private static CategoryRecords instance;
	private ArrayList<Category> categories;
	
	private CategoryRecords()
	{
		this.categories = new ArrayList<>();
	}

	public static CategoryRecords getInstance() 
	{
		if(instance == null)
        {
            instance = new CategoryRecords();
        }
		return instance;
	}
	
	public ArrayList<Category> getCategories() {
		return categories;
	}
	
	public void setCategories(ArrayList<Category> categories) {
		this.categories = categories;
	}
	
	public void addCategory(Category category)
	{
		categories.add(category);
	}
	
	public Category getCategoryByTitle(String title)
	{
		Category theCategory = null;
		boolean found = false;
		Iterator<Category> it = categories.iterator();
		while (it.hasNext() && !found) 
		{
			Category category = it.next();
			if(category.getTitle()==title)
			{
				theCategory = category;
				found = true;
			}			
		}
		return theCategory;
	}
	
	//method to update a category
		//done by category
		public void updateCategory(String wantedTitle, String newTitle, double newDiscount )
		{
			Category category=getCategoryByTitle(wantedTitle);
			if(category!=null)
			{
				category.setTitle(newTitle);
				category.setDiscount(newDiscount);
				for(Customer customer : CustomerRecords.getInstance().getCustomers())
				{
					if(customer.getcategory().getTitle()==wantedTitle)
					{
						customer.setCategory(new Category("not set", 0));
					}
				}
			}
			else
			{
				System.out.println("Please insert a valid category title.");
			}
		}
		
		//method to delete a category
		//done by title of category
		public void deleteCategory(String wantedTitle)
		{
			Category wantedCategory=null;
			Category category=getCategoryByTitle(wantedTitle);
			wantedCategory=category;
			if(wantedCategory!=null)
			{
				categories.remove(wantedCategory);
				for(Customer customer : CustomerRecords.getInstance().getCustomers())
				{
					if(customer.getcategory().getTitle()==wantedTitle)
					{
						customer.setCategory(new Category("not set", 0));
					}
				}
			}
			else
			{
				System.out.println("Please insert a valid category title.");
			}
		}	

	
    public void printCategories()
	{
		for(Category category: categories)
		{
			System.out.println("Title of category: " + category.getTitle() + "  Discount: " + category.getDiscount());
		}
	}
}
